<template>
  <div class="page-wrap">
    <div class="search-form">
      <el-form ref="searchFormRef" :model="queryForm" inline size="small">
        <el-form-item label="账户名称" prop="accountName">
          <el-input v-model="queryForm.accountName" v-trim class="form-width" clearable></el-input>
        </el-form-item>
        <el-form-item label="真实姓名" prop="realName">
          <el-input v-model="queryForm.realName" v-trim class="form-width" clearable></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input v-model="queryForm.phone" v-trim class="form-width" clearable></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="queryForm.email" v-trim class="form-width" clearable></el-input>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="queryForm.status" class="form-width" clearable>
            <el-option label="启用" :value="1"></el-option>
            <el-option label="禁用" :value="0"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button v-debounce="1000" type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="operate-btns-group">
      <el-button type="primary" @click="handleEdit(null)">新增</el-button>
    </div>
    <el-table
      ref="tableRef"
      :data="tableData"
      border
      class="table"
      :height="tableHeight"
      style="width: 100%">
      <el-table-column prop="accountName" label="账户名称" min-width="80" show-overflow-tooltip/>
      <el-table-column prop="realName" label="真实姓名" min-width="80" show-overflow-tooltip/>
      <el-table-column prop="phone" label="手机号" min-width="120" show-overflow-tooltip/>
      <el-table-column prop="email" label="邮箱" min-width="160" show-overflow-tooltip/>
      <el-table-column prop="statusText" label="账户状态" min-width="80" show-overflow-tooltip/>
      <el-table-column prop="typeText" label="账号类型" min-width="80" show-overflow-tooltip/>
      <el-table-column prop="itsmStatusText" label="ITSM用户状态" min-width="120" show-overflow-tooltip/>
      <el-table-column prop="roles" label="角色" min-width="80" show-overflow-tooltip/>
      <el-table-column prop="creator" label="创建者" min-width="100" show-overflow-tooltip/>
      <el-table-column prop="createTime" label="创建时间" min-width="120" show-overflow-tooltip/>
      <el-table-column prop="updator" label="更新者" min-width="100" show-overflow-tooltip/>
      <el-table-column prop="updateTime" label="更新时间" min-width="120" show-overflow-tooltip/>
      <el-table-column fixed="right" label="操作" width="120">
        <template #default="{row}">
          <svg-button
            content="修改"
            icon="Edit"
            is-el-icon
            @click="handleEdit(row)"
          />
          <svg-button
            content="删除"
            icon="Delete"
            is-el-icon
            color="#F56C6C"
            :loading="row.delLoading"
            @click="handleDel(row)"
          />
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      v-model:current-page="currentPage"
      :page-sizes="pageSizes"
      :page-size="pageSize"
      :total="total"
      layout="total, sizes, prev, pager, next, jumper, slot"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange">
      <button text @click="handleRefresh">
        <el-icon :size="20">
          <Refresh />
        </el-icon>
      </button>
    </el-pagination>

    <edit-sample-dialog
      v-model:visible="editSampleDialogData.visible"
      :pdata="editSampleDialogData.data"
      @dialog-confirm-event="handleSearch"/>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed, toRaw } from 'vue'
import { awaitWrap, setDefaultEmptyValueForObject } from '@/utils'
import { SUCCESS_CODE } from '@/constants'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getAccountList, delAccount } from '@/api/account-management'
import { useTableCommonData } from '@/composables/table-common'
import EditSampleDialog from './EditAccountDialog.vue'
import SvgButton from '@/components/SvgButton/index.vue'
import { getTextByEnum } from '@/utils/enum'
import { useStore } from 'vuex'

// 生命周期函数
onMounted(() => {
  handleSearch()
})

// 组件实例
const tableRef = ref()

// ---------------------------获取表格数据---------------------
// 表格查询项的初始数据
const query = {
  accountName: null, // 账户名
  realName: null, // 真实姓名
  phone: null, // 电话
  email: null, // 邮箱
  status: null // 状态
}
// 设置提交参数
const setParams = () => {
  return {
    accountName: queryFormSubmit.value.accountName,
    realName: queryFormSubmit.value.realName,
    phone: queryFormSubmit.value.phone,
    email: queryFormSubmit.value.email,
    status: queryFormSubmit.value.status
  }
}
// 获取表格参数
const getTableData = async () => {
  const params = {
    ...setParams(),
    currentPage: currentPage.value,
    pageSize: pageSize.value
  }
  const { res } = await awaitWrap(getAccountList(params, { loadingDom: '.table' }))
  if (res?.statusCode === SUCCESS_CODE) {
    const rows = res.data?.rows || []
    total.value = res.data?.total || 0
    tableData.value = []
    rows.forEach(v => {
      const item = {
        fid: v.fid,
        accountName: v.faccountName, // 账号名称
        realName: v.frealName, // 真实姓名
        status: v.fstatus, // 状态
        statusText: getTextByEnum(v.fstatus, 'BOOLEAN_STATUS_ENUM'), // 状态
        creator: v.fcreator,
        createTime: v.fcreateTime,
        updator: v.fupdator,
        updateTime: v.fupdateTime,
        email: v.femail,
        phone: v.fphone,
        roles: v.froles,
        typeText: getTextByEnum(v.ftype, 'USER_TYPE_ENUM'), // SSO版本特有字段--账号类型（1内部账号 2外部账号）
        type: v.ftype, // SSO版本特有字段--账号类型（1内部账号 2外部账号）
        itsmStatusText: getTextByEnum(v.fitsmStatus, 'BOOLEAN_STATUS_ENUM'), // SSO版本特有字段--ITSM用户状态（0：禁用；1：启用)
        itsmStatus: v.fitsmStatus// SSO版本特有字段--ITSM用户状态（0：禁用；1：启用)
      }
      item.realData = item
      setDefaultEmptyValueForObject(item)
      tableData.value.push(item)
    })
  }
}

// 表格基础数据
const {
  tableData,
  currentPage,
  pageSize,
  pageSizes,
  total,
  queryForm,
  queryFormSubmit,
  tableHeight,
  handleSearch,
  handleReset,
  handleSizeChange,
  handleCurrentChange,
  handleRefresh
} = useTableCommonData({ query, getTableDataFn: getTableData })

// ---------------------按钮交互操作相关内容-------------------
// 编辑样本弹窗数据
const editSampleDialogData = reactive({
  data: null,
  visible: false
})
// 编辑
const handleEdit = row => {
  editSampleDialogData.data = row ? { ...row } : null
  editSampleDialogData.visible = true
}

// -------------------------删除-------------------------------
const store = useStore()
const userInfo = computed(() => {
  return toRaw(store.getters.userInfo)
})
const handleDel = async row => {
  // 判断是否是账户本身
  if (row.fid === userInfo.value.id) {
    ElMessage.error('不能删除本身账号')
    return
  }
  const msg = `确定删除${row.accountName}吗？`
  await ElMessageBox.confirm(msg, '提示')
  row.delLoading = true
  const { res } = await awaitWrap(delAccount(row.fid))
  if (res?.success) {
    handleSearch()
  }
  row.delLoading = false
}

// 表格基础方法

</script>

<style lang="scss">
.form-width{
  width: 200px;
}
</style>
